package it.unical.canonaco.rende.igpe.game.cbv.guilayer.gamemanagermenu.storemenu.itemshop;

import it.unical.canonaco.rende.igpe.game.cbv.guilayer.components.ImageCache;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.components.OverallGUILayoutFactory;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.components.ThinScrollBar;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.gamemanagermenu.storemenu.StorePanel;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.BagClickEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.CharBoughtEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.CharacterClickEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.GraphicEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.GraphicEventListener;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.GraphicEventManager;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.ItemBoughtEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.ItemSoldEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.ShopItemClickEvent;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.pawn.items.Item;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.pawn.items.ItemFactory;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.pawn.stats.Stats;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.managers.StoreManager;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

class ItemShopPanel extends JPanel implements GraphicEventListener {
	
	private static final long serialVersionUID = -6671899346329621442L;
	private JButton buyButton;
	private JButton sellButton;
	private JLabel playerGoldLabel = new JLabel();
	final private JTree itemsTree;
	private static String BUY = "COMPRA";
	private static String SELL = "VENDI";
	
	private GraphicEventManager gem;
	private StoreManager storeManager;
	private ImageCache imgCache;
	private HashMap<String, String> settings;
	private OverallGUILayoutFactory guiCreator = OverallGUILayoutFactory.getInstance();
	
	ItemShopPanel(final GraphicEventManager gem, final HashMap<String, String> settings,
					 final StoreManager storeManager, ImageCache imgCache) {
		
		this.gem = gem;
		this.settings = settings;
		this.storeManager = storeManager;
		this.imgCache = imgCache;
		
		gem.addListener(this, CharacterClickEvent.class);
		gem.addListener(this, ShopItemClickEvent.class);
		gem.addListener(this, ItemBoughtEvent.class);
		gem.addListener(this, ItemSoldEvent.class);
		gem.addListener(this, BagClickEvent.class);
		gem.addListener(this, CharBoughtEvent.class);
		
		GridBagConstraints gbc = new GridBagConstraints();
		this.setOpaque(false);
		this.setLayout(new GridBagLayout());
		
		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
		DefaultMutableTreeNode categoryNode;
		DefaultMutableTreeNode itemNode;
		
		itemsTree = new JTree(rootNode);
	
		itemsTree.setVisibleRowCount(10);
		itemsTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		itemsTree.addTreeSelectionListener(new TreeSelectionListener() {
			
			@Override
			public void valueChanged(TreeSelectionEvent arg0) {
				 
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) itemsTree.getLastSelectedPathComponent();
				 
				Item item = null;
				
				 if(node == null)
					 return;
				
				 Object nodeInfo = node.getUserObject();
				 
				 if(node.getLevel() == 2)
					 item = (Item) nodeInfo;
					 
				 storeManager.setCurrentSelectedItem(item);
		
				 gem.fireEvent(new ShopItemClickEvent(item));
					 
			}
		});
		
		ItemFactory itmfct = ItemFactory.getInstance();
		itmfct.loadAll(null);
//	
	for(int i = 0; i<Stats.TOTAL_STATISTICS; i++){
		categoryNode = new DefaultMutableTreeNode(i);
		rootNode.add(categoryNode);
	
	for(Item itm :  itmfct.sortByValue(itmfct.getItemStats() ).values() ) {
		if(itm.getStats(i) > 0) {
		itemNode = new DefaultMutableTreeNode(itm);
		categoryNode.add(itemNode);
		}
	}
	}
		itemsTree.setCellRenderer(new ItemTreeCellRenderer(settings, imgCache));
		
		// set "categories" to be displayed (they are collapsed into (hidden, see below) root by default)
		itemsTree.expandRow(0);
		// disable root visibility (must be called after all visibility settings, such as expandRow)
		itemsTree.setRootVisible(false);
		// expands/collpases categories by single clicking (default is double click, setToggleClickCount(2))
		// or with left or right arrows
		itemsTree.setToggleClickCount(1);
		itemsTree.setOpaque(false);
		JScrollPane scrollPane = new JScrollPane(itemsTree,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//		scrollPane.getViewport().setOpaque(false);
		scrollPane.setVerticalScrollBar(new ThinScrollBar(JScrollBar.VERTICAL));
		scrollPane.setPreferredSize(new Dimension(400,250));
//		BackgroundImageJViewport bgview = new BackgroundImageJViewport(image);
//		bgview.setOpaque(false);
//		scrollPane.setViewport(bgview);
		scrollPane.setBackground(Color.decode("#ede2b1"));
		scrollPane.getViewport().setOpaque(false);
//		scrollPane.setOpaque(false);
//		scrollPane.getViewport().setBorder(null);
//		scrollPane.setBorder(BorderFactory.createBevelBorder(5,Color.red,Color.LIGHT_GRAY));
		scrollPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.DARK_GRAY.brighter(),2), 
				BorderFactory.createLineBorder(Color.decode("#ede2b1"),5) ));
		
		gbc.insets = new Insets(Integer.parseInt(settings.get(StorePanel.INSET_TOP)),
				Integer.parseInt(settings.get(StorePanel.INSET_LEFT)),Integer.parseInt(settings.get(StorePanel.INSET_BOTTOM)),
				Integer.parseInt(settings.get(StorePanel.INSET_RIGHT)));
		gbc.gridx = 1;
		gbc.gridy = 0;
		gbc.gridheight = 8;
		gbc.anchor = GridBagConstraints.PAGE_START;
		this.add(scrollPane, gbc);
		
		gbc.gridy = 8;
		gbc.gridheight = 1;
		Image coinImg = imgCache.getImage(settings.get(StorePanel.COIN_IMAGE));
		playerGoldLabel.setHorizontalTextPosition(JLabel.LEFT);
		playerGoldLabel.setText(storeManager.getPlayer().getGold()+StorePanel.SPACE);
		playerGoldLabel.setIcon(new ImageIcon(coinImg.getScaledInstance(coinImg.getWidth(null)/Integer.parseInt(settings.get(StorePanel.COIN_SCALE)),
				coinImg.getWidth(null)/Integer.parseInt(settings.get(StorePanel.COIN_SCALE)), Image.SCALE_SMOOTH)));
		playerGoldLabel.setBackground(new Color(226,243,253,100));
		playerGoldLabel.setOpaque(true);
		try {
			Font font = Font.createFont(Font.TRUETYPE_FONT, new File("cbvapps/uiresource/data/sharksoftbites.ttf"));
			playerGoldLabel.setFont(font.deriveFont(Font.PLAIN,20));
		} catch (FontFormatException | IOException e) {
			e.printStackTrace();
		}
		
		this.add(playerGoldLabel, gbc);
		
		gbc.gridy = 9;
		buyButton = guiCreator.createButtonUniState(40, BUY, 150,50, OverallGUILayoutFactory.BUTTON_STATE_ACTIVE);
		buyButton.setEnabled(false);
		buyButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				storeManager.buyItem();
				gem.fireEvent(new ItemBoughtEvent());
			}
		});
		this.add(buyButton, gbc);
		
		gbc.gridy = 10;
		sellButton = guiCreator.createButtonUniState(40, SELL, 150,50, OverallGUILayoutFactory.BUTTON_STATE_ACTIVE);
		sellButton.setPreferredSize(buyButton.getPreferredSize());
		sellButton.setEnabled(false);
		sellButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				 JOptionPane pane = new JOptionPane();
				 final JDialog dialog = new JDialog(new JFrame(),true);
				 JPanel dialogPanel = new JPanel(new GridBagLayout());
				 dialog.setPreferredSize(new Dimension(300,50));
				 dialogPanel.setBackground(Color.LIGHT_GRAY);
				 JButton sellButton = new JButton("SI");
				 sellButton.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent arg0) {
							storeManager.sellItem();
							gem.fireEvent(new ItemSoldEvent());
							closeJDialog(dialog);
						}
					});
				 JButton cancelButton = new JButton("NO");
				 cancelButton.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent arg0) {
							closeJDialog(dialog);			
						}
					});
				 JLabel selling = new JLabel("VUOI VENDERE L'OGGETTO?");
				 GridBagConstraints gbc = new GridBagConstraints();
				 gbc.gridx = 0;
				 gbc.gridy = 0;
				 gbc.gridwidth = 2;
				 gbc.weightx = 1;
				 dialogPanel.add(selling,gbc);
				 gbc.anchor = GridBagConstraints.PAGE_START;
				 gbc.gridwidth = 1;
				 gbc.gridx = 0;
				 gbc.gridy = 1;
				 dialogPanel.add(sellButton,gbc);
				 gbc.gridx = 1;
				 gbc.gridy = 1;
				 dialogPanel.add(cancelButton,gbc);
				 dialog.add(dialogPanel);
//					dialogPanel.requestFocusInWindow();
				 dialog.setUndecorated(true);
//				 dialog.setLocationRelativeTo(thes);
				 dialog.pack();
				 dialog.setLocationRelativeTo(ItemShopPanel.this);
				
				 dialog.setVisible(true);
				 revalidate(); // If a component has been added to a container that has been displayed, validate must be called on that container to display the new component.
//					if(javax.swing.SwingUtilities.isEventDispatchThread()) System.out.println("yes");
			}
		});
		this.add(sellButton, gbc);
	}

	@Override
	public void notify(GraphicEvent event) {
		
		checkButtons();
	
//			itemsTree.clearSelection();
		if ( event.getClass() == ItemBoughtEvent.class || event.getClass() == ItemSoldEvent.class
				|| event.getClass() == CharBoughtEvent.class){
			
			playerGoldLabel.setText(storeManager.getPlayer().getGold()+StorePanel.SPACE);
		}
	}
	

		
	private void checkButtons(){
		if(storeManager.getCurrentSelectedItem() == null || storeManager.isInventoryFull() 
				|| !storeManager.isPriceAffordable() || storeManager.givesNegativeStats())
			buyButton.setEnabled(false);
		else buyButton.setEnabled(true);
		if(storeManager.getCurrentSelectedBag() != StoreManager.NONE && !storeManager.isSlotFree())
		sellButton.setEnabled(true);
		else sellButton.setEnabled(false);
	}
	

	/**
	 * @param dialog
	 */
	private void closeJDialog(final JDialog dialog) {
		dialog.setVisible(false);
		dialog.dispose();
	}
	
	}// end ItemPanel class